//
//  WordsVC.m
//  sweetbox
//
//  Created by apollo on 15/9/8.
//  Copyright (c) 2015年 proj-m. All rights reserved.
//

#import "WordsVC.h"
#import "log.h"
#import "DBHelper.h"
#import "WordsMD.h"
#import "WordVC.h"

@interface WordsVC ()
@property (nonatomic, strong) WordsMD *dataSource;
@property (nonatomic, strong) NSMutableDictionary *words;
@property (nonatomic, strong) NSArray *index;
@end

@implementation WordsVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
    [nc addObserver:self
           selector:@selector(onSaveWord)
               name:@"save_word"
             object:nil];

    
    self.dataSource = [[WordsMD alloc] init];
    UITableView *view = (UITableView *) self.view;
    view.dataSource = self;
    view.delegate = self;
    self.words = [[NSMutableDictionary alloc] init];
    self.index = [[NSMutableSet alloc] init];
    
    [self refreshWords];
    NSLog(@"View Did Load");
}

- (void) refreshWords {
    [self.words removeAllObjects];
    NSMutableSet *keys = [[NSMutableSet alloc]init];
    int wordNum = [[DBHelper sharedDBHelper] countWrods];
    for (int i=0;i<wordNum;i++) {
        NSArray *word = [[DBHelper sharedDBHelper] wordAt:i];
        char idxLetter = [(NSString *)word[0] characterAtIndex:0];
        NSString *capKey = [NSString stringWithFormat:@"%c",toupper(idxLetter)];
        [keys addObject: capKey];
        NSMutableArray *capGroup = [self.words objectForKey: capKey];
        if (nil == capGroup) {
            capGroup = [[NSMutableArray alloc] init];
        }
        [capGroup addObject:word];
        [self.words setObject:capGroup forKey:capKey];
    }
    NSArray *sortDesc = @[[[NSSortDescriptor alloc] initWithKey:nil ascending:YES]];
    self.index = [keys sortedArrayUsingDescriptors:sortDesc];
}

- (void) onSaveWord {
    [self refreshWords];
    UITableView *view = (UITableView *) self.view;
    [view reloadData];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)onNew:(id)sender {
    UIViewController *vc  =(UIViewController *) [[UIStoryboard storyboardWithName:@"dictionary" bundle:nil] instantiateViewControllerWithIdentifier:@"new_word"];
    if (nil != vc) {
        vc.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
        [self presentViewController:vc animated:YES completion:^(){
            LOG_I("After Come into New Ward Page");
        }];
    }
}


#pragma mark - UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSString *key = self.index[section];
    NSMutableArray *subArray = [self.words objectForKey:key];
    if (nil == subArray) {
        return 0;
    }
    return subArray.count;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.index.count;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    return self.index[section];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"cell"];
    NSString *key = self.index[indexPath.section];
    NSArray *word = [[self.words objectForKey:key] objectAtIndex:indexPath.row];
    if (nil == word) {
        cell.textLabel.text = @"";
        return cell;
    }
    cell.textLabel.text = word[0];
    cell.detailTextLabel.text = word[1];
    cell.selectionStyle = UITableViewCellSelectionStyleNone; // set cell not height by can by touch on tableview
    cell.accessoryType =  UITableViewCellAccessoryDisclosureIndicator; // jump tringle icon
    return cell;
}


 - (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView { // A...Z sort
     return self.index;
 }


#pragma mark - UITableDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSLog(@"select at %d row",(int)indexPath.row);
    WordVC *vc  =(WordVC *) [[UIStoryboard storyboardWithName:@"dictionary" bundle:nil] instantiateViewControllerWithIdentifier:@"word"];
    UINavigationController *navVC  =  (UINavigationController *)self.parentViewController;
    NSString *key = self.index[indexPath.section];
    vc.word = [[self.words objectForKey:key] objectAtIndex:indexPath.row][0];
    [navVC pushViewController:vc animated:YES];
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        NSString *key = self.index[indexPath.section];
        NSArray *word = [[self.words objectForKey:key] objectAtIndex:indexPath.row];
        if (nil == word) {
            LOG_E("Cur row not in self.words");
            return ;
        }
        [[DBHelper sharedDBHelper] deleteWord:word[0]];
        [[self.words objectForKey:key] removeObjectAtIndex:indexPath.row];
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationBottom];
    }
}



@end
